<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_category\Entity\ShusyCategory;
use Drupal\shusy_product\Entity\ShusyProduct;
use Drupal\ssy_index_products\Entity\SsyIndexProducts;
use Drupal\ssy_index_products\Entity\SsyIndexProductsItem;

class IndexProductsBoxItem extends AbstractBaseModel {

  protected function getEntityType() {
    return 'ssy_index_products';
  }

  protected function getQuery(int $category_id) {
    $query = '';
    $category = shusy_category_load($category_id);
    if ($category instanceof ShusyCategory) {
      switch ($category->depth) {
        case 0:
          $query = "depth_1:{$category->depth_1}";
          break;
        case 1:
          $query = "depth_2:{$category->depth_2}";
          break;
        case 2:
          $query = "depth_3:{$category->depth_3}";
          break;
      }
    }
    return $query;
  }

  protected function setValue() {
    if ($this->entity instanceof SsyIndexProducts) {
      $products = $this->getProducts($this->entity);
      $query = $this->getQuery($this->entity->category_id);
      $url = "/pages/index/goodslist/goodslist?op=query&query={$query}";
      $value = [
        'name' => (string) $this->entity->name,
        'sort' => (int) $this->entity->sort,
        'products' => $products,
        'url' => $url,
      ];
      $this->merge($value);
    }
  }

  protected function getProducts(SsyIndexProducts $products) {
    $list = [];
    $es = ssy_index_products_item_load_multiple(FALSE, [
      'index_products_id' => $products->id,
      'status' => 1,
    ]);
    foreach ($es as $e) {
      if ($e instanceof SsyIndexProductsItem) {
        $product = shusy_product_load($e->product_id);
        if ($product instanceof ShusyProduct) {
          $list[] = ProductItem::init($e->product_id);
        }
      }
    }
    return $list;
  }

}
